﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Crosland.Automotriz.Facade.Interface;
using Crosland.Automotriz.Facade.Facade;
using Crosland.Automotriz.Core;
using System.Threading;
using Crosland.Automotriz.Logic.Linq;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using System.Configuration;
using Crosland.Automotriz.Seguridad.DataAccess;
using Crosland.Automotriz.Logic.ControlExeption;

namespace Crosland.Automotriz.Web.Repuestos
{
    public partial class wFrmManualesPartesVehiculos : System.Web.UI.Page
    {
        private String idNegocio = ConfigurationManager.AppSettings["Negocio"];
        private iFacadeSistema cls_man_modelo_imagenlogic = new FacadeSistema();
        private static String strMsg;


        protected void Page_Load(object sender, EventArgs e)
        {

            


            if (!IsPostBack)
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", "JavaScript:confirmSubmitResult();", true);
                cboMarca.SelectedIndex = 0;
                listarMArca();
                FiltraModelo();
            }
        }

        private void listarArticulo()
        {
            try
            {
                int intIndex = (Session["intIndex"] != null) ? Convert.ToInt32(Session["intIndex"]) : gvsistema.FocusedRowIndex;

                if (intIndex == -1) return;

                int intIdSistema = Convert.ToInt32(gvsistema.GetRowValues(intIndex, "ID_SISTEMA"));
                int intIdModelo = Convert.ToInt32(gvsistema.GetRowValues(intIndex, "ID_MODELO"));
                int intNroPag = Convert.ToInt32(gvsistema.GetRowValues(intIndex, "NRO_PAGINA"));

                gvPopDetalleArticulos.DataSource = cls_man_modelo_imagenlogic.listar_sistema_articulo(intIdSistema, intIdModelo, intNroPag);
                gvPopDetalleArticulos.DataBind();
                lblnropagina.Text = intNroPag.ToString().Trim();

                String imgUrl = String.Format("{0}/{1}", ConfigurationManager.AppSettings["RutaFotoSistema"], gvsistema.GetRowValues(intIndex, "DES_IMAGEN"));
                imagen.ImageUrl = imgUrl;
                lbldes_sistema.Text = String.Format("{0} - {1}", gvsistema.GetRowValues(intIndex, "DES_SISTEMA_INGLES").ToString().Trim(), gvsistema.GetRowValues(intIndex, "DES_SISTEMA").ToString().Trim());
                Session["DES_URL"] = imgUrl;
                Session["DES_SISTEMA"] = Convert.ToString(gvsistema.GetRowValues(intIndex, "DES_SISTEMA"));
                Session["intIndex"] = intIndex;
                gvsistema.FocusedRowIndex = intIndex;
            }
            catch (RunException exc)
            {
                GuardarExceptionLog(exc.Message, exc, "listarArticulo");
                MensajesError(exc.Message, exc, "listarArticulo");
            }
        }

        private void listarMArca()
        {
            try
            {
                clsTD_MarcaLogic cltMarcalogic = new clsTD_MarcaLogic();
                cboMarca.DataSource = cltMarcalogic.ListarMarcaActivo();
                cboMarca.TextField = "DES_MARCA";
                cboMarca.ValueField = "COD_MARCA";
                cboMarca.DataBind();
            }
            catch (RunException exc)
            {
                GuardarExceptionLog(exc.Message, exc, "listarMArca");
                MensajesError(exc.Message, exc, "listarMArca");
            }

        }

        private void SistemaPagAnterior()
        {
            try
            {
                if (PCTab.ActiveTabIndex != 1)
                {
                    MostrarComentario("Debe seleccionar un sistema.");
                    return;
                }

                int intIndex = (Session["intIndex"] != null) ? Convert.ToInt32(Session["intIndex"]) : gvsistema.FocusedRowIndex;
                int intIndexPage = gvsistema.VisibleStartIndex;

                if (intIndexPage > (intIndex - 1))
                {
                    if (gvsistema.PageIndex == 0)
                    {
                        strMsg = "No hay mas registros hacia atrás.";
                        MostrarComentario(strMsg);
                        return;
                    }

                    if (gvsistema.PageIndex > 0) gvsistema.PageIndex--;
                }

                Session["intIndex"] = (intIndex - 1);
                listarArticulo();
            }
            catch (RunException exc)
            {
                GuardarExceptionLog(exc.Message, exc, "SistemaPagAnterior");
                MensajesError(exc.Message, exc, "SistemaPagAnterior");
            }
        }

        private void SistemaPagSiguiente()
        {
            try
            {
                if (PCTab.ActiveTabIndex != 1)
                {
                    MostrarComentario("Debe Seleccionar Un Sistema.");
                    return;
                }

                int intIndex = (Session["intIndex"] != null) ? Convert.ToInt32(Session["intIndex"]) : gvsistema.FocusedRowIndex;
                int intMaxIndexPage = gvsistema.VisibleStartIndex + gvsistema.GetCurrentPageRowValues().Count();

                if (intIndex == (intMaxIndexPage - 1))
                {
                    if (gvsistema.PageIndex == (gvsistema.PageCount - 1))
                    {
                        strMsg = "No hay mas registros hacia adelante.";
                        MostrarComentario(strMsg);
                        return;
                    }

                    if (gvsistema.PageIndex < (gvsistema.PageCount - 1)) gvsistema.PageIndex++;
                }

                Session["intIndex"] = (intIndex + 1);
                listarArticulo();
            }
            catch (RunException exc)
            {
                GuardarExceptionLog(exc.Message, exc, "SistemaPagSiguiente");
                MensajesError(exc.Message, exc, "SistemaPagSiguiente");
            }
        }

        private void MostrarComentario(String strMsg)
        {
            CargarAlert(strMsg, "Mensaje");
        }

        private void CargarAlert(String strMsg, String strTitulo)
        {
            pcMensaje.HeaderText = strTitulo;
            lblmsj.Text = strMsg;
            pcMensaje.ShowOnPageLoad = true;
        }

        private void FiltraModelo()
        {
            try
            {
                dvModeloImagen.DataSource = cls_man_modelo_imagenlogic.listar_Modelo_XT_Man_Modelo_Imagen(cboMarca.Text, cboTipoRueda.Text);
                dvModeloImagen.DataBind();
            }
            catch (RunException exc)
            {
                GuardarExceptionLog(exc.Message, exc, "FiltraModelo");
                MensajesError(exc.Message, exc, "FiltraModelo");
            }
        }

        protected void gvsistema_FocusedRowChanged(object sender, EventArgs e)
        {
            Session["intIndex"] = gvsistema.FocusedRowIndex;
            listarArticulo();
        }

        protected void gvModelo_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            FiltraModelo();
        }

        protected void gvModelo_PageIndexChanged(object sender, EventArgs e)
        {
            FiltraModelo();
        }

        protected void gvsistema_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            if (Convert.ToInt32(Session["intIndex"]) == -1)
            {
                gvsistema.FocusedRowIndex = -1;
            }
            gvsistema.DataSource = cls_man_modelo_imagenlogic.listar_filtro_modelo_sistema(Convert.ToInt32(Session["id_modelo"]));
            gvsistema.DataBind();

        }

        protected void gvsistema_PageIndexChanged(object sender, EventArgs e)
        {
            gvsistema.DataSource = cls_man_modelo_imagenlogic.listar_filtro_modelo_sistema(Convert.ToInt32(Session["id_modelo"]));
            gvsistema.DataBind();
        }

        protected void gvArticulo_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            listarArticulo();
        }

        protected void gvArticulo_PageIndexChanged(object sender, EventArgs e)
        {
            listarArticulo();
        }

        protected void Timer2_Tick(object sender, EventArgs e)
        {

        }

        protected void gvPopDetalleArticulos_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            listarArticulo();
        }

        protected void dvModeloImagen_ItemCommand(object source, DevExpress.Web.ASPxDataView.DataViewItemCommandEventArgs e)
        {
            string[] arg = new string[2];
            arg = e.CommandArgument.ToString().Split(';');
            String strIdModelo, strDesModelo;
            try
            {
                strIdModelo = arg[0].Trim();
                strDesModelo = arg[1].Trim();

                Session["id_modelo"] = strIdModelo;
                Session["DES_MODELO"] = strDesModelo;
                int intIdModelo = (strIdModelo != String.Empty) ? Convert.ToInt32(strIdModelo) : 0;
                gvsistema.DataSource = cls_man_modelo_imagenlogic.listar_filtro_modelo_sistema(intIdModelo);
                gvsistema.DataBind();
                PCTab.ActiveTabIndex = 1;
                if (intIdModelo != 0)
                {
                    lblModelo.Text = Session["DES_MODELO"].ToString();
                    lblModelo0.Text = Session["DES_MODELO"].ToString();
                }
                else
                {
                    lblModelo.Text = "";
                    lblModelo0.Text = "";
                }
            }
            catch (RunException exc)
            {
                GuardarExceptionLog(exc.Message, exc, "dvModeloImagen_ItemCommand");
                MensajesError(exc.Message, exc, "dvModeloImagen_ItemCommand");
            }
        }

        protected void btnFiltral_Click(object sender, EventArgs e)
        {
            FiltraModelo();
        }

        protected void btnSalir_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Seguridad/wFrmDefault.aspx?id=" + idNegocio);
        }

        protected void PCTab_TabClick(object source, DevExpress.Web.ASPxTabControl.TabControlCancelEventArgs e)
        {
            gvsistema.FocusedRowIndex = -1;
        }

        protected void btnSPagAnt_Click(object sender, EventArgs e)
        {
            SistemaPagAnterior();
        }

        protected void btnSPagSgte_Click(object sender, EventArgs e)
        {
            SistemaPagSiguiente();
        }

        private void GuardarExceptionLog(String msgUsu, Exception ex, String metError)
        {
            try
            {
                String msgReal, fhError, pagError, codUsu;
                msgReal = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
                pagError = new System.IO.FileInfo(Page.Request.Url.AbsolutePath).Name;
                codUsu = Session["User"].ToString();
                fhError = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"); 
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                int number = 0;
                for (int i = 0; i < trace.FrameCount; i++)
                {
                    System.Diagnostics.StackFrame sf = trace.GetFrame(i);
                    number = sf.GetFileLineNumber();
                }
                fhError = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
                new Logg().ErrorLog(Server.MapPath("~/Logs/ErrorLog.csv"), msgUsu, msgReal, pagError, metError, codUsu, number);
            }
            catch (DataException e)
            {
                MensajesError(e.Message, e, "GuardarExceptionLog");
            }
            catch (RunException re)
            {
                MensajesError(re.Message, re, "GuardarExceptionLog");
            }

        }

        private void MensajesError(String msgUsu, Exception ex, String metError)
        {
            Crosland.Automotriz.Web.UserControl.MensajeError uc = (Crosland.Automotriz.Web.UserControl.MensajeError)Master.FindControl("ucErrorMensaje");
            String msgReal, fhError, pagError, codUsu;
            msgReal = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
            pagError = new System.IO.FileInfo(Page.Request.Url.AbsolutePath).Name;
            codUsu = Session["User"].ToString();
            fhError = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
            System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
            int number = 0;
            for (int i = 0; i < trace.FrameCount; i++)
            {
                System.Diagnostics.StackFrame sf = trace.GetFrame(i);
                number = sf.GetFileLineNumber();
            }
            uc.Errores(msgUsu, msgReal, fhError, pagError, metError, codUsu, number);
        }

    }
}
